package com.study.demo.controller;

import com.study.demo.common.CommonUtil;
import com.study.demo.dto.BasicResponse;
import com.study.demo.dto.TokenDto;
import com.study.demo.dto.User;
import com.study.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/login")
    public BasicResponse<TokenDto> login(@RequestParam String name, @RequestParam String password) {
        User user = userService.findByNameAndPassword(name, password);
        BasicResponse<TokenDto> basicResponse = new BasicResponse<TokenDto>();
        if (user == null || !name.equals(user.getName()) || !password.equals(user.getPassword())) {
            return null;
        }
        //生成token
        String token  = CommonUtil.createToken();
        redisTemplate.opsForValue().set(token, user, Duration.ofMinutes(30));
        TokenDto tokenDto = new TokenDto();
        tokenDto.setToken(token);
        basicResponse.setValue(tokenDto);
        return basicResponse;
    }

    @GetMapping("/changePwd")
    public String changePwd(@RequestParam String name,
                            @RequestParam String password,
                            @RequestParam String newPwd) {
        userService.changePwd(name, password, newPwd);
        redisTemplate.delete("login::" + name);
        return "success";
    }
}
